package com.fdb.basic.framework.core.util;

public class HexUtils {
    /** 转换数据 */
    private static final char[] HEXDIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    public static byte[] hex2Byte(String str) {
        if (str == null)
            return null;
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1)
            return null;
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer
                        .decode("0x" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }

    public static String byte2Hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toUpperCase();
    }

    public static String str2HexStr(String str){
        StringBuilder sb=new StringBuilder("");
        byte[] bs=str.getBytes();
        int bit;
        for(int i=0;i<bs.length;i++){
            bit=(bs[i]&0x0f0)>>4;
            sb.append(HEXDIGITS[bit]);
            bit=bs[i]&0x0f;
            sb.append(HEXDIGITS[bit]);
        }
        return sb.toString().trim();
    }
}
